package com.android.lovely.ui.fragment.image

import android.Manifest
import android.app.Activity
import android.content.Context
import android.net.Uri
import android.os.Build
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.net.toUri
import androidx.core.view.isVisible
import com.android.lovely.R
import com.android.lovely.databinding.LayoutCardGuideBinding
import com.android.lovely.databinding.WidgetFaceRetentionBinding
import com.android.lovely.ext.getActivity
import com.android.lovely.ext.loadWithPlaceholder
import com.android.lovely.ext.startImageCrop
import com.android.lovely.framework.BaseFragment
import com.android.lovely.ui.widget.CreateRoleTitleView.OnTitleClickListener
import com.google.android.material.internal.ViewUtils.hideKeyboard
import com.kotlin.extensions.inflater.LayoutInflaterExt.layoutInflater
import com.kotlin.extensions.keyboard.hideKeyboard
import com.kotlin.extensions.view.ViewExt.clickable
import com.yalantis.ucrop.UCrop

/**
 *
 * @author why
 * @date 2025/4/10 14:43
 */
class FaceRetentionView: BaseFragment<WidgetFaceRetentionBinding>()  {

    private var uri: Uri? = null

    // 存储权限请求启动器
    private val storagePermissionRequestLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isPermissionGranted ->
        handleStoragePermissionRequestResult(isPermissionGranted)
    }

    // 裁剪活动启动器
    private val imageCropActivityLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
        handleImageCropActivityResult(activityResult)
    }

    // 头像选择启动器
    private val avatarSelectionLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { selectedAvatarUri ->
        handleAvatarSelectionResult(selectedAvatarUri)
    }

    // 处理存储权限请求结果
    private fun handleStoragePermissionRequestResult(isPermissionGranted: Boolean) {
        if (isPermissionGranted) {
            startAvatarSelection()
        }
    }

    // 处理裁剪活动结果
    private fun handleImageCropActivityResult(activityResult: ActivityResult) {
        if (activityResult.resultCode == Activity.RESULT_OK) {
            val resultIntent = activityResult.data ?: return
            val croppedAvatarUri = UCrop.getOutput(resultIntent) ?: return
            updateAvatar(croppedAvatarUri)
        }
    }

    // 处理头像选择结果
    private fun handleAvatarSelectionResult(selectedAvatarUri: Uri?) {
        selectedAvatarUri?.let {
            startImageCrop(it)
        }
    }

    // 启动头像选择
    private fun startAvatarSelection() {
        avatarSelectionLauncher.launch("image/*")
    }

    // 启动图片裁剪
    private fun startImageCrop(avatarUri: Uri) {
        requireActivity().startImageCrop(imageCropActivityLauncher, avatarUri, isCircleCrop = false)
    }

    // 更新头像
    private fun updateAvatar(avatarUri: Uri) {
        this.uri = avatarUri
        mBinding.ivAvatar.loadWithPlaceholder(avatarUri, R.drawable.icon_default_avatar)
    }

    fun updateAvatar(url: String, isCheck: Boolean) {
        this.uri = url.toUri()
        mBinding.ivAvatar.loadWithPlaceholder(uri, R.drawable.icon_default_avatar)
        mBinding.cvTitle.changeSwitch(isCheck)
    }


    override fun initView() {
        mBinding.cvTitle.addCallback(object : OnTitleClickListener{
            override fun onSelect(isOpen: Boolean) {
                requireActivity().hideKeyboard()
                mBinding.clAvatar.isVisible = isOpen
                mBinding.cvTitle.showDesc2(isOpen)
            }

        })
        mBinding.ivAvatar.clickable {
            requireActivity().hideKeyboard()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                avatarSelectionLauncher.launch("image/*")
                return@clickable
            }
            storagePermissionRequestLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
    }

    override suspend fun initData() {

    }

    fun check(): Boolean {
        return  (mBinding.cvTitle.getCheck() && uri != null) || !mBinding.cvTitle.getCheck()
    }

    fun clear() {
        mBinding.cvTitle.changeSwitch(false)
        mBinding.clAvatar.isVisible = false
        mBinding.ivAvatar.setImageResource(R.drawable.icon_role_avatar_default)
    }

    fun getUri(): Uri? {
        return uri
    }

    fun getFaceCheck(): Boolean {
        return mBinding.cvTitle.getCheck()
    }

}